package org.smartboot.flow.custom;

import org.smartboot.flow.core.Extensible;
import org.smartboot.flow.core.attribute.ValueHolder;
import org.smartboot.flow.core.manager.ComponentModel;
import org.smartboot.flow.core.manager.XmlGenerator;
import org.smartboot.flow.core.manager.XmlRevertExtension;
import org.smartboot.flow.helper.view.PlantumlConvertExtension;
import org.smartboot.flow.helper.view.PlantumlGenerator;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author qinluo
 * @date 2024-08-18 23:19:16
 * @since 1.0.0
 */
public class TransactionComponentExtensionImpl implements XmlRevertExtension, PlantumlConvertExtension {

    @Override
    public List<String> getNonStandardAttributeBlacklist(Extensible model, Map<String, ValueHolder> nonStandardAttributes) {
        if (Objects.equals(model.getNonStandardAttributeExpress("tag"), "transaction-component")) {
            return Arrays.asList("tag", "prefix", "transactionManager");
        }
        return null;
    }

    @Override
    public void generate(ComponentModel model, XmlGenerator generator, int whitespaces) {
        if (Objects.equals(model.getNonStandardAttributeExpress("tag"), "transaction-component")) {
            String prefix = model.getNonStandardAttributeExpress("prefix");

            generator.addNamespace(prefix, "http://org.smartboot/smart-flow/transaction-component", "http://org.smartboot/smart-flow/transaction-component.xsd");

            generator.appendWhitespaces(whitespaces);
            generator.append("<").append(prefix).append(":transaction-component").append(" transactionManager=\"")
                    .append(model.getNonStandardAttributeExpress("transactionManager")).append("\"");
            generator.generateAttributes(model, whitespaces + 24 + prefix.length());
            generator.append(">").newline(false);

            generator.generate(model.getComponentModels().get(0), whitespaces + 4);
            generator.appendWhitespaces(whitespaces).append("</").append(prefix).append(":transaction-component/>").newline(false);

        }
    }

    @Override
    public void generatePlantumlContent(ComponentModel model, PlantumlGenerator generator) {
        if (Objects.equals(model.getNonStandardAttributeExpress("tag"), "transaction-component")) {
            generator.addSubprocess("事物子流程", model.getName() + "-" + model.getNonStandardAttributeExpress("transactionManager"), () -> generator.generate(model.getComponentModels().get(0)));
        }
    }
}
